/* eslint-disable react-hooks/rules-of-hooks */
import React, { useState } from "react";
import { Modal, Button, Form, Input, Checkbox, message } from "antd";
import { invokeAPi } from "@/xz-fn.js";
import "./index.css";

const ModalContact = ({ openContact, hideContact }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleOk = () => {
    form.validateFields().then(async (values) => {
      setLoading(true);
      try {
        const params = {
          email: values.email,
          company: values.company || "",
          phone: values.phone || "",
          message: values.message,
          subscribe: values.subscribe ? 1 : 0,
        };
        const res = await invokeAPi("xz_contact_us", params);
        if (res.code === 200) {
          message.success("提交成功！");
          hideContact();
          form.resetFields();
        } else {
          message.error(res.msg || "提交失败，请重试。");
        }
      } catch (error) {
        console.error("提交错误:", error);
        message.error("提交失败，请重试。");
      } finally {
        setLoading(false);
      }
    });
  };

  const handleCancel = () => {
    hideContact();
    form.resetFields();
  };

  return (
    <Modal
      title="联系我们"
      open={openContact}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      centered
      footer={[
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
          提交
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical" name="contact_us_form">
        <Form.Item
          name="email"
          label="电子邮箱"
          rules={[
            { required: true, message: "请输入您的电子邮箱!" },
            { type: "email", message: "请输入有效的电子邮箱地址!" },
          ]}
        >
          <Input placeholder="请输入您的电子邮箱" />
        </Form.Item>
        <Form.Item name="company" label="公司名称">
          <Input placeholder="请输入您的公司名称" />
        </Form.Item>
        <Form.Item name="phone" label="电话号码">
          <Input placeholder="请输入您的电话号码" />
        </Form.Item>
        <Form.Item
          name="message"
          label="留言内容"
          rules={[{ required: true, message: "请输入您的留言内容!" }]}
        >
          <Input.TextArea rows={4} placeholder="请输入您的留言内容" />
        </Form.Item>
        <Form.Item name="subscribe" valuePropName="checked" noStyle>
          <Checkbox>
            我同意接收 AnythingLLM 的邮件更新和新闻
          </Checkbox>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ModalContact;
